//
//  UserFollowViewController.m
//  danpin
//
//  Created by chuangjia on 2/9/15.
//  Copyright (c) 2015 chuangjia. All rights reserved.
//

#import "UserFollowViewController.h"

#import "CellConfig.h"
#import "viewconfig.h"
#import "SVPullToRefreshView+OY_PullRefreshView.h"
#import "BaseModel.h"
#import "ZToastManager.h"
#import "OtherUserCenterVC.h"

@interface UserFollowViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    
}
@property(nonatomic,strong)NSMutableArray *datasArray;
@property(nonatomic,strong)UITableView *tbView;
@property(nonatomic,assign)BOOL isLoadFinished;
@property(nonatomic,assign)BOOL isRequesting;
@property(nonatomic,assign)int currentPage;
@property(nonatomic,assign)BOOL isRefresh;
@property(nonatomic,strong)NSString *action;
@end

@implementation UserFollowViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [UMengShare event:CK_USERDETAIL acc:1];
    self.isComment = YES;
    self.navTitle =@"关注";
    
    if (!_datasArray) {
        _datasArray =[[NSMutableArray alloc] init];
    }
    self.isLoadFinished =NO;
    self.isRequesting = NO;
    self.currentPage = 0;
    self.action=@"recommend";
    [self initUI];
    [self loadData:self.action];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)dealloc
{
    self.action=nil;
    [self.datasArray removeAllObjects];
    self.datasArray=nil;
    self.tbView.dataSource=nil;
    self.tbView.delegate=nil;
    self.tbView=nil;
}
-(void)initUI
{
    _tbView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.navHeight, self.view.frame.size.width, self.view.frame.size.height-self.navHeight) style:UITableViewStylePlain];
    _tbView.delegate = self;
    _tbView.dataSource = self;
    _tbView.backgroundColor = [UIColor clearColor];
    _tbView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tbView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_tbView];
    
    self.currentPage = 0;
    
    __weak typeof (self) wSelf = self;
    
    [_tbView addPullToRefreshWithActionHandler:^{
        wSelf.isRequesting = YES;
        wSelf.isRefresh = NO;
        wSelf.currentPage = 0;
        [wSelf.tbView.pullToRefreshView startAnimating];
        [wSelf  loadData:wSelf.action];
    }];
    //
    //
    [_tbView.pullToRefreshView setOYStyle];
    //
    // setup infinite scrolling
    [self.tbView addInfiniteScrollingWithActionHandler:^{
        if (wSelf.isRequesting) {
            return ;
        }
        wSelf.isRefresh = NO;
        if (wSelf.isLoadFinished) {
            //停止菊花
            [wSelf.tbView.infiniteScrollingView stopAnimating];
            [wSelf.tbView setShowsInfiniteScrolling:NO];
            return;
        }
        [wSelf.tbView.infiniteScrollingView startAnimating];
        wSelf.currentPage =(int) [wSelf.datasArray count];
        [wSelf  loadData:wSelf.action];
        
    }];
    
    
}
#pragma mark - tableview
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.datasArray.count;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dict =[self.datasArray objectAtIndex:indexPath.row];
    return [UserFollowCell returnCellHeight:dict];
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UserFollowCell *cell = (UserFollowCell*)[tableView  dequeueReusableCellWithIdentifier:@""];
    if(cell == nil)
    {
        cell = [[UserFollowCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
        cell.backgroundColor=[UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        _tbView.separatorStyle = UITableViewCellSeparatorStyleNone;
        __weak typeof (self) wSelf = self;
        [cell setCallBack:^(BEventType t, UIView *v,id obj,id key,NSIndexPath *indexPath) {
            [wSelf cellAction:t views:v obj:obj key:key indexPath:indexPath];
        }];
    }
    NSDictionary *dict =[self.datasArray objectAtIndex:indexPath.row];
    [cell showInfo:dict key:@"followRecommed" indexPath:indexPath];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row>=self.datasArray.count) {
        return;
    }
    NSDictionary *user =[self.datasArray objectAtIndex:indexPath.row];
    OtherUserCenterVC *userf =[[OtherUserCenterVC alloc] init];
    NSMutableDictionary *dict =[NSMutableDictionary dictionary];

    NSString*largeFace =  [[NSString stringWithFormat:@"%@",[user objectForKey:@"largeFace"]] replaceNullString];
    NSString*user_id =  [[NSString stringWithFormat:@"%@",[user objectForKey:@"user_id"]] replaceNullString];
    NSString*nick_name =  [[NSString stringWithFormat:@"%@",[user objectForKey:@"nick_name"]] replaceNullString];
    
    [dict setValue:largeFace forKey:@"largeFace"];
    [dict setValue:user_id forKey:@"user_id"];
    [dict setValue:nick_name forKey:@"nick_name"];
    
    userf.userDictionary=dict;
    [self.navigationController pushViewController:userf animated:YES];
}

-(void)cellAction:(BEventType)type views:(UIView *)v obj:(id)obj key:(id)key indexPath:(NSIndexPath *)indexPath
{
    switch (type) {
        case BEventType_userfollow:
        {
            if ([self isLogin]){
                NSString *pid =[NSString stringWithFormat:@"%@",[obj objectForKey:@"user_id"]];
                NSString *nickname =[NSString stringWithFormat:@"%@",[obj objectForKey:@"nick_name"]];
                NSMutableDictionary *dict =[NSMutableDictionary dictionary];
                [dict setValue:@"follow_user" forKey:@"action"];
                [dict setValue:@"" forKey:@"brand_id"];
                [dict setValue:@"" forKey:@"cate_id"];
                [dict setValue:pid forKey:@"follow_id"];
                [dict setValue:nickname forKey:@"follow_name"];
                [dict setValue:@"" forKey:@"tag"];
                __weak typeof (self) wSelf = self;
                [BaseModel follow:dict success:^(AFHTTPRequestOperation* operation, id result){
                    
                    if (result&&[result isKindOfClass:[NSDictionary class]]) {
                        NSDictionary *resultDist =(NSDictionary*)result;
                        [[ZToastManager ShardInstance] showtoast:[resultDist objectForKey:@"msg"]];
                        [wSelf.datasArray removeObjectAtIndex:indexPath.row];
                        [wSelf.tbView reloadData];
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"updateLoveList" object:pid];
                    }
                    
                } failure:^(NSError* error){
                    [[ZToastManager ShardInstance] showtoast:@"取消关注失败"];
                }];
            }
        }
            break;
        default:
            break;
    }
}
-(void)loadData:(NSString*)action
{
    NSMutableDictionary *dict =[NSMutableDictionary dictionary];
    [dict setValue:action forKey:@"action"];
    [dict setValue:[NSString stringWithFormat:@"%d",self.currentPage] forKey:@"from"];
    __weak typeof (self) wSelf = self;
    
    wSelf.isRequesting = YES;
    [BaseModel userlist:dict allowFetchCache:NO success:^(AFHTTPRequestOperation *operation, id result) {
        [wSelf parserResultObject:result];
        wSelf.isRequesting = NO;
        wSelf.isRefresh =NO;
        [wSelf.tbView.pullToRefreshView stopAnimating];
        [wSelf.tbView.infiniteScrollingView stopAnimating];
        [ZShare hiddenAnimationView:wSelf.view];
    } failure:^(NSError *error) {
        wSelf.isRequesting = NO;
        wSelf.isRefresh =NO;
        [wSelf.tbView.pullToRefreshView stopAnimating];
        [wSelf.tbView.infiniteScrollingView stopAnimating];
        [ZShare hiddenAnimationView:wSelf.view text:@""];
    }];
}
-(void)parserResultObject:(id)resultObject
{
    [[ZToastManager ShardInstance] hideprogress];
    if (resultObject==nil) {
        return;
    }
    if (resultObject && [resultObject isKindOfClass:[NSDictionary class]]) {
        id data =  [resultObject objectForKey:@"data"];
        if (data && [data isKindOfClass:[NSArray class]]){
            if (self.currentPage==0) {
                [self.datasArray removeAllObjects];
            }
            for (id dict in data) {
                [self.datasArray addObject:dict];
            }
        }
        id no_data =  [resultObject objectForKey:@"no_data"];
        if (no_data&&[no_data isKindOfClass:[NSString class]]) {
            [ZShare hiddenAnimationView:self.view text:no_data];
            self.tbView.tableFooterView =nil;
        }else {
            [ZShare hiddenAnimationView:self.view];
        }
        self.isLoadFinished =  [[resultObject objectForKey:@"end"] boolValue];
        
        if (self.isLoadFinished) {
            NSString *end_msg =[resultObject objectForKey:@"end_msg"];
            self.tbView.tableFooterView =[ZShare footerView:end_msg];
            
            
            [self.tbView.infiniteScrollingView stopAnimating];
            [self.tbView setShowsInfiniteScrolling:NO];
        }
    }
    [self.tbView reloadData];
    self.isRequesting = NO;
}
@end
